
const {findTag} = require('../service/tag.service')

const {
  tagFormateError,
  tagIdFormateError,
  tagDoesNotExist,
  tagAlreadyExited,
  tagInsertError
} = require('../constant/err.type')

// 验证标签是否为空
const tagValidator = async (ctx, next) => {
  const {tag_name} = ctx.request.body;
  if(!tag_name) {
    console.error('标签名为空', ctx.request.body)
    ctx.response.body = tagFormateError
    return
  }
  await next()
}

// 验证标签id是否为空
const tagIdValidator = async (ctx, next) => {
  const {id} = ctx.request.body;
  if(!id) {
    ctx.response.body = tagIdFormateError
    return
  }
  await next()
}

// 验证标签id是不存在
const hasNotTag = async (ctx, next) => {
  const {id} = ctx.request.body;
  try {
    const res = await findTag({id})
    if(!res || res.length === 0 ) {
      console.error('不存在此标签id', ctx.request.body)
      ctx.response.body = tagDoesNotExist
      return
    }
  } catch(err) {
    console.log('获取标签信息错误', err)
    ctx.response.body = tagInsertError
    return
  }
  await next()
}

// 验证标签名是否存在
const hasTag = async (ctx, next) => {
  const {tag_name} = ctx.request.body;

  try {
    const res = await findTag({tag_name})
    if(res && res.length > 0) {
      console.error('该标签已经存在，请勿重复添加！', ctx.request.body)
      ctx.response.body = tagAlreadyExited
      return
    } 
  } catch(err) {
    console.error('获取标签信息错误', err)
    ctx.response.body = tagInsertError
    return
  }
  await next()
}

module.exports = {tagValidator, tagIdValidator, hasTag, hasNotTag}